package com.han.walkman.controller;

import com.han.walkman.entity.DocumentEntity;
import com.han.walkman.service.DocumentService;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/5/2
 * @Desc:
 */
@RestController
@RequestMapping("/document")
public class DocumentController {
    private final DocumentService documentService;

    public DocumentController(DocumentService documentService) {
        this.documentService = documentService;
    }

    /**
     * 分页查询
     *
     * @return list
     */
    @GetMapping("/findAll")
    public List<DocumentEntity> findAll() {
        return documentService.findAll();
    }

    /**
     * 分页查询
     *
     * @return list
     */
    @GetMapping("/findByKeyword")
    public Page<DocumentEntity> findByPage(String keyword, Integer index, Integer size) {

        //构建搜索条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //忽略大小写
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        DocumentEntity entity = new DocumentEntity();
        entity.setTitle(keyword);
        Example<DocumentEntity> entityExample = Example.of(entity, exampleMatcher);

        Pageable pageable = PageRequest.of(index, size);
        return documentService.findAll(entityExample, pageable);
    }

    @GetMapping("/findById")
    public DocumentEntity findById(Integer id) {
        Optional<DocumentEntity> entityOptional = documentService.findById(id);
        return entityOptional.orElse(null);
    }

    /**
     * 查询文件list
     *
     * @return 剔除掉不需要参数的list
     */
    @GetMapping("/findStarFile")
    public List<DocumentEntity> findStarFile() {
        DocumentEntity entity = new DocumentEntity();
        entity.setStar(true);
        Example<DocumentEntity> entityExample = Example.of(entity);
        return documentService.findAll(entityExample);
    }
}
